package com.itheima.reggie.interceptor;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.EmployeeHolder;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.damain.Employee;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//拦截器
@Component
public class LoginCheck implements HandlerInterceptor {
    //拦截未登录账户 进入其他页面的活动
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从session中获取登陆成功之后存储信息
        Employee employee= (Employee) request.getSession().getAttribute("STATUS_ENABLE");
        if (employee==null){
            //未登录，使用json返回
            String json=JSON.toJSONString(ResultInfo.error("NOTLOGIN"));

            response.getWriter().write(json);


            //返回false
            return false;
    }else {
            //加入单线程，线程内信息共享
            EmployeeHolder.set(employee);
            return true;
        }
}

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        EmployeeHolder.remove();
    }
}
